import { reactive, toRefs, computed } from "vue"
import { onShow, onUnload, onReady, onLoad } from "@dcloudio/uni-app";
import { LoginStore } from "@/store/modules/login";
import config from "@/config/config";
const uniIdCo = uniCloud.importObject("uni-id-co", { customUI: true })
/**
 * @description  设置新密码
 * @param rules 表单校验规则
 * */
export const useSetPwd = (formRefs, rules) => {
	const state = reactive({
		formData: {
			code: '', //验证码	
			password: "", //密码
			password2: '' //对比密码
		},
		formItem: {
			loading: false, //防抖状态
			allowSkip: false //是否允许跳过设置密码
		},
		uniIdRedirectUrl: '', //路由地址
		loginType: '', //登录类型
		// 校验规则
		rules
	})
	onLoad((e) => {
		if (config.setPasswordAfterLogin && config.setPasswordAfterLogin?.allowSkip) {
			state.formItem.allowSkip = true
		}
		state.uniIdRedirectUrl = e.uniIdRedirectUrl
		state.loginType = e.loginType
		state.formData.code = e.code
	})
	// 兼容H5
	onShow(() => {
		// #ifdef H5
		document.onkeydown = event => {
			var e = event || window.event;
			if (e && e.keyCode == 13) { //回车键的键值为13
				submit()
			}
		};
		// #endif
	})
	onReady(() => {
		// 兼容小程序的校验 (uview中使用)
		if (formRefs.value.setRules) formRefs.value.setRules(state.rules)
	});


	// 卸载键盘事件
	onUnload(() => {
		// #ifdef H5
		document.onkeydown = false
		// #endif
	});
	/**
	 * @description: 设置密码
	 * @param {*} formRef 表单实例
	 * @param {*} rules 验证规则
	 */
	const submit = async () => {
		formRefs.value.validator(state.formData, rules).then(async res => {
			if (!res.isPassed) return
			try {
				state.formItem.loading = true
				const data = await uniIdCo.setPwd({
					password: state.formData.password,
					code: state.formData.code,
				})
				uni.showModal({
					content: '密码设置成功',
					showCancel: false,
					success: () => {
						const LoginState = LoginStore()
						LoginState.loginBack({
							uniIdRedirectUrl: state.uniIdRedirectUrl,
							loginType: state.loginType
						})
						state.formItem.loading =false
					}
				});
			} catch (e) {
				uni.showModal({
					content: e.message,
					showCancel: false
				});
			}
		})
	}

	// 跳过登录
	const toPage = () => {
		const LoginState = LoginStore()
		LoginState.loginBack({
			uniIdRedirectUrl: state.uniIdRedirectUrl,
		})
	}

	return {
		...toRefs(state),
		submit,
		toPage
	};
};